#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <iostream>
#include <cstring>


const char* SOCKET_PATH = "/tmp/example.sock";
const int BUFFER_SIZE = 1024;

int main() {
    // 创建UNIX域套接字
    int server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (server_fd == -1) {
        perror("socket creation failed");
        return 1;
    }

    // 绑定套接字到文件路径
    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path) - 1);

    // 删除可能已存在的套接字文件
    unlink(SOCKET_PATH);

    if (bind(server_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        perror("bind failed");
        close(server_fd);
        return 1;
    }

    // 开始监听
    if (listen(server_fd, 5) == -1) {
        perror("listen failed");
        close(server_fd);
        return 1;
    }

    std::cout << "Server is listening on " << SOCKET_PATH << std::endl;

    // 主循环
    while (true) {
        // 接受客户端连接
        int client_fd = accept(server_fd, nullptr, nullptr);
        if (client_fd == -1) {
            perror("accept failed");
            continue;
        }

        char buffer[BUFFER_SIZE];
        ssize_t bytes_read;

        // 读取客户端命令
        while ((bytes_read = read(client_fd, buffer, sizeof(buffer))) > 0) {
            // 处理命令 (这里简单回显)
            std::cout << "Received command: " << buffer << std::endl;
            
            // 发送响应
            if (write(client_fd, buffer, bytes_read) != bytes_read) {
                perror("write failed");
                break;
            }
            
            memset(buffer, 0, sizeof(buffer));
        }

        if (bytes_read == -1) {
            perror("read failed");
        }

        close(client_fd);
    }

    close(server_fd);
    unlink(SOCKET_PATH);
    return 0;
}